package larpplanner.gui;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import larpplanner.database.Player;
import larpplanner.database.Quest;

import com.cloudgarden.resource.SWTResourceManager;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.SWT;

public class CharWin extends org.eclipse.swt.widgets.Dialog {

	private Quest quest;
	
	private GUISafeLARPManager mngr = GUISafeLARPManager.get();

	private Map<String, Long> playerNamesAndIds;
	private Long newPlayerId = -1L;
	private String newPlayerName_d = null;
	private String newPlayerCharName_d;
	
	private Shell dialogShell;
	private Label charDetailsLbl;
	private UniverseCharacterPanel univCharPanel;
	private Composite charDetComp;
	private Label charNameLbl;
	private Text charTxt;
	private Label charPic;
	private Composite playerDetComp;
	private Combo playerNameCombo;
	private Label playerPhoneLbl;
	private Label playerMailLbl;
	private Button okBtn;

	
	/**
	 * 	use this CTOR when editing an existing player
	 */
	public CharWin(Shell parent, int style, Quest quest, String playerName) {
		super(parent, style);
		this.quest = quest;
		initGui();
		initLogic();
		if(playerName != null && !playerName.equals("")) {
			//set player to be the given player
			String[] items = new String[1];
			items[0] = playerName;
			playerNameCombo.setItems(items);
			playerNameCombo.setText(playerName);
			playerNameCombo.setEnabled(false);
			//TODO: set universe and character also
		}else
			getPlayersFromMngr();
	}
	
	public void setCharNameLbl(String name) {
		charNameLbl.setText(name);
	}
	
	public void setOkBtnEnabled(boolean enabled) {
		okBtn.setEnabled(enabled);
	}
	
	public int getPlayerComboIndex() {
		return playerNameCombo.getSelectionIndex();
	}
	
	public void setCharDetailsText(String text) {
		charTxt.setText(text);
	}
	
	public void setCharName(String charName) {
		newPlayerCharName_d = charName;
	}
	
	public String getCharName() {
		return newPlayerCharName_d;
	}
	
	public String getPlayerName() {
		return newPlayerName_d;
	}
	
	private void getPlayersFromMngr() {
		// get all players names
		mngr.getAll(Player.class, new SafeCallback<List<Player>>() {
			public void onReturn(List<Player> returnedList) {
				playerNamesAndIds = new TreeMap<String,Long>();
				for(Player p : returnedList)
					playerNamesAndIds.put(p.getName(), p.getId());
				// this isn't working because we do not change the quest's players list when adding or removing
				// remove players that are already in the quest
				//for(Player p : quest.getParticipants().keySet())
				//	playerNamesAndIds.remove(p.getName());
				String[] playerNamesArray = playerNamesAndIds.keySet().toArray(new String[0]);
				playerNamesArray = addToStringArr(playerNamesArray, "<select player>");
				playerNameCombo.setItems(playerNamesArray);
				playerNameCombo.setText(playerNamesArray[0]);
			}
		});
	}
	
	
	private void initLogic() {
		
		okBtn.setEnabled(false);
		
		playerNameCombo.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				newPlayerName_d = playerNameCombo.getText();
				if(univCharPanel.getCharComboIndex() > 0 && playerNameCombo.getSelectionIndex() > 0)
					okBtn.setEnabled(true);
				else
					okBtn.setEnabled(false);
			}
		});
		
		okBtn.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				
				mngr.addParticipant(quest.getId(), playerNamesAndIds.get(playerNameCombo.getText()), univCharPanel.getCharId(), new SafeCallback<Long>() {
					public void onReturn(Long result) {
						if(result == -1)
							PopMessage.errorMessage("character dialog: quest update failed");
						else{
							newPlayerId = result;
							
						}
						dialogShell.dispose();
					}
				});
			}
		});
	}
	
	public static void main(String[] args) {
		try {
			Display display = Display.getDefault();
			Shell shell = new Shell(display);
			CharWin inst = new CharWin(shell, SWT.NULL, new Quest(), null);
			inst.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Long open() {
		try{
			dialogShell.setLocation(getParent().toDisplay(100, 100));
			dialogShell.open();
			Display display = dialogShell.getDisplay();
			while (!dialogShell.isDisposed()) {
				if (!display.readAndDispatch())
					display.sleep();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newPlayerId;
	}
	
	private String[] addToStringArr(String[] a, String s) {
		String[] res = new String[a.length + 1];
		res[0] = s;
		for(int i = 1 ; i < res.length ; i++)
			res[i] = a[i-1];
		return res;
	}

	private void initGui() {
		try {
			Shell parent = getParent();
			dialogShell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
			SWTResourceManager.registerResourceUser(dialogShell);
			
			GridLayout dialogShellLayout = new GridLayout();
			dialogShellLayout.makeColumnsEqualWidth = true;
            dialogShellLayout.numColumns = 1;
            dialogShellLayout.marginTop = 5;
            dialogShellLayout.marginRight = 5;
            dialogShellLayout.marginLeft = 5;
            dialogShellLayout.marginBottom = 5;
            dialogShell.setLayout(dialogShellLayout);
            dialogShell.layout();
            dialogShell.pack();            
            dialogShell.setSize(490, 400);
            dialogShell.setText("Character Selection");
			{
				charDetailsLbl = new Label(dialogShell, SWT.NONE);
				GridData charDetailsLblLData = new GridData();
				charDetailsLblLData.widthHint = 450;
				charDetailsLblLData.grabExcessHorizontalSpace = true;
				charDetailsLbl.setLayoutData(charDetailsLblLData);
				charDetailsLbl.setText("Character Details");
				charDetailsLbl.setFont(SWTResourceManager.getFont("Lucida Calligraphy", 14, 0, false, false));
			}
			{
				univCharPanel = new UniverseCharacterPanel(dialogShell, SWT.NONE, this);
				RowLayout univCharHolderLayout = new RowLayout(org.eclipse.swt.SWT.HORIZONTAL);
				GridData univCharHolderData = new GridData();
				univCharPanel.setLayoutData(univCharHolderData);
				univCharPanel.setLayout(univCharHolderLayout);
			}
			{
				charDetComp = new Composite(dialogShell, SWT.BORDER);
				GridLayout charDetCompLayout = new GridLayout();
				charDetCompLayout.numColumns = 2;
				GridData charDetCompLData = new GridData();
				charDetCompLData.horizontalAlignment = GridData.FILL;
				charDetComp.setLayoutData(charDetCompLData);
				charDetComp.setLayout(charDetCompLayout);
				{
					charNameLbl = new Label(charDetComp, SWT.NONE);
					GridData charNameLblData = new GridData();
					charNameLblData.grabExcessHorizontalSpace = true;
					charNameLblData.horizontalSpan = 2;
					charNameLbl.setLayoutData(charNameLblData);
					charNameLbl.setText("<char name goes here>");
					charNameLbl.setFont(SWTResourceManager.getFont("Bookman Old Style", 12, 0, false, false));
				}
				{
					charTxt = new Text(charDetComp, SWT.MULTI | SWT.WRAP | SWT.BORDER);
	                GridData charTxtData = new GridData();
	                charTxtData.grabExcessHorizontalSpace = true;
	                charTxtData.widthHint = 304;
	                charTxtData.verticalAlignment = GridData.FILL;
	                charTxt.setLayoutData(charTxtData);
	                charTxt.setText("<char information here>");
	                charTxt.setEditable(false);
				}
				{
					charPic = new Label(charDetComp, SWT.NONE);
					GridData charPicData = new GridData();
					charPicData.verticalAlignment = GridData.BEGINNING;
					charPic.setLayoutData(charPicData);
					charPic.setImage(SWTResourceManager.getImage("img/Ares.jpg"));
				}
			}
			{
				playerDetComp = new Composite(dialogShell, SWT.BORDER);
				GridLayout playerDetCompLayout = new GridLayout();
				playerDetCompLayout.numColumns = 2;
				playerDetCompLayout.makeColumnsEqualWidth = true;
				GridData playerDetCompLData = new GridData();
				playerDetCompLData.grabExcessHorizontalSpace = true;
				playerDetCompLData.horizontalAlignment = GridData.FILL;
				playerDetComp.setLayoutData(playerDetCompLData);
				playerDetComp.setLayout(playerDetCompLayout);
			
				{
					playerNameCombo = new Combo(playerDetComp, SWT.READ_ONLY);
					GridData playerNameLblData = new GridData();
					playerNameLblData.horizontalSpan = 2;
                    playerNameLblData.widthHint = 140;
					playerNameCombo.setLayoutData(playerNameLblData);
				}
				{
					playerPhoneLbl = new Label(playerDetComp, SWT.BORDER);
					GridData playerPhoneLblData = new GridData();
					playerPhoneLblData.grabExcessHorizontalSpace = true;
					playerPhoneLblData.horizontalAlignment = GridData.FILL;
					playerPhoneLbl.setLayoutData(playerPhoneLblData);
					playerPhoneLbl.setText("phone:");
				}
				{
					playerMailLbl = new Label(playerDetComp, SWT.BORDER);
					GridData playerMailLblData = new GridData();
					playerMailLblData.grabExcessHorizontalSpace = true;
					playerMailLblData.horizontalAlignment = GridData.FILL;
					playerMailLbl.setLayoutData(playerMailLblData);
					playerMailLbl.setText("mail:");
				}
			}
			{
				okBtn = new Button(dialogShell, SWT.NONE);
				GridData okBtnLData = new GridData();
				okBtnLData.heightHint = 23;
				okBtnLData.horizontalAlignment = GridData.FILL;
				okBtn.setLayoutData(okBtnLData);
				okBtn.setText("OK");
				okBtn.setSize(60, 25);
			}
		} catch (Exception e) {
            e.printStackTrace();
        }
	}
}
